package flc.ast.fragment;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.stark.picselect.entity.SelectMediaEntity;
import com.youth.banner.listener.OnBannerListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import flc.ast.AppConfig;
import flc.ast.R;
import flc.ast.activity.DetailActivity;
import flc.ast.activity.MovieActivity;
import flc.ast.adapter.MovieAdapter;
import flc.ast.adapter.MyBannerAdapter;
import flc.ast.bean.MyCollectBean;
import flc.ast.bean.MyVideoBean;
import flc.ast.databinding.FragmentMovieBinding;
import flc.ast.utils.AppSpUtils;
import flc.ast.utils.Content;
import stark.common.api.StkApi;
import stark.common.api.StkResApi;
import stark.common.base.IReqRetCallback;
import stark.common.basic.base.BaseNoModelFragment;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.IntentUtil;
import stark.common.bean.StkResBean;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link MovieFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class MovieFragment extends BaseNoModelFragment<FragmentMovieBinding> {

    private MovieAdapter movieAdapter;

    @Override
    protected int onCreate() {
        return R.layout.fragment_movie;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(getActivity(), mDataBinding.event1Container);
        EventStatProxy.getInstance().statEvent5(getActivity(), mDataBinding.event5Container);
        mDataBinding.tvMovieMore.setOnClickListener(this);
        mDataBinding.rvRecommendList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        movieAdapter = new MovieAdapter();
        mDataBinding.rvRecommendList.setAdapter(movieAdapter);
        movieAdapter.addChildClickViewIds(R.id.ivRecommendItemCollect);
        movieAdapter.setOnItemChildClickListener(this);
        movieAdapter.setOnItemClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()){
            case R.id.tvMovieMore:
                startActivity(MovieActivity.class);
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        StkResBean bean=movieAdapter.getItem(position);
        DetailActivity.detail=bean;
        startActivity(DetailActivity.class);
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
        StkResBean bean = movieAdapter.getItem(position);
        switch (view.getId()) {
            case R.id.ivRecommendItemCollect:
                List<MyCollectBean> listSp = AppSpUtils.getCollectList();
                if (movieAdapter.getItem(position).isSelected()) {
                    for (MyCollectBean myCollectBean : listSp) {
                        if (myCollectBean.getPath().equals(bean.getThumbUrl())) {
                            listSp.remove(myCollectBean);
                            break;
                        }
                    }
                    AppSpUtils.saveCollectList(listSp);
                } else {
                    List<MyCollectBean> listSave = new ArrayList<>();
                    try {
                        Gson gson = new Gson();
                        String json = gson.toJson(bean.getExtra());
                        JSONObject jsonObject = new JSONObject(json);
                        String releaseDate = jsonObject.getString("releaseDate");
                        int index = releaseDate.indexOf("(");
                        String dateStr = releaseDate.substring(0, index);
                        Date date = TimeUtils.string2Date(dateStr, new SimpleDateFormat("yyyy-MM-dd"));
                        if (date==null){
                            date=TimeUtils.string2Date(dateStr, new SimpleDateFormat("yyyy"));
                        }
                        listSave.add(new MyCollectBean(bean.getName(), bean.getThumbUrl(), date.getTime()));
                        if (listSp != null && listSp.size() != 0) {
                            listSp.addAll(listSave);
                            AppSpUtils.saveCollectList(listSp);
                        } else {
                            AppSpUtils.saveCollectList(listSave);
                        }
                    } catch (JSONException e) {
                        throw new RuntimeException(e);
                    }
                }
                getMovieData();
                break;
        }
    }

    @Override
    protected void initData() {
        getBannerData();
        getMovieData();
    }

    private void getBannerData() {
        StkResApi.getTagResourceList(this, AppConfig.BANNER_DATA, StkApi.createParamMap(0, 5), false,
                new IReqRetCallback<List<StkResBean>>() {
                    @Override
                    public void onResult(boolean success, String msg, @Nullable List<StkResBean> result) {
                        if (success) {
                            if (result != null && result.size() > 0) {
                                for (StkResBean stkResBean : result) {
                                    List<MyCollectBean> listSp = AppSpUtils.getCollectList();
                                    if (listSp != null && listSp.size() != 0) {
                                        for (MyCollectBean myCollectBean : listSp) {
                                            if (myCollectBean.getPath().equals(stkResBean.getThumbUrl())) {
                                                stkResBean.setSelected(true);
                                                break;
                                            }
                                        }
                                    } else {
                                        break;
                                    }
                                }
                                MyBannerAdapter bannerAdapter = new MyBannerAdapter(result, getContext());
                                mDataBinding.movieBanner.setAdapter(bannerAdapter, true);//false不无限循环
                                mDataBinding.movieBanner.setBannerGalleryEffect(30, 24);//40两边露出距离，20图片之间距离
                                mDataBinding.movieBanner.isAutoLoop(true);//false不自动轮播
                                //点击监听
                                mDataBinding.movieBanner.setOnBannerListener(new OnBannerListener() {
                                    @Override
                                    public void OnBannerClick(Object data, int position) {
                                        StkResBean bean=bannerAdapter.getData(position);
                                        DetailActivity.detail=bean;
                                        startActivity(DetailActivity.class);
                                    }
                                });
                            }
                        }
                    }
                });
    }

    private void getMovieData() {
        StkResApi.getTagResourceList(null, AppConfig.MOVIE_DATA, StkApi.createParamMap(0, 5),
                new IReqRetCallback<List<StkResBean>>() {
                    @Override
                    public void onResult(boolean success, String msg, @Nullable List<StkResBean> result) {
                        if (success) {
                            if (result != null && result.size() > 0) {
                                for (StkResBean stkResBean : result) {
                                    List<MyCollectBean> listSp = AppSpUtils.getCollectList();
                                    if (listSp != null && listSp.size() != 0) {
                                        for (MyCollectBean myCollectBean : listSp) {
                                            if (myCollectBean.getPath().equals(stkResBean.getThumbUrl())) {
                                                stkResBean.setSelected(true);
                                                break;
                                            }
                                        }
                                    } else {
                                        break;
                                    }
                                }
                                movieAdapter.setList(result);
                            }
                        }
                    }
                });
    }

}